
#include "ijksdl_linux_vout.h"

#include <assert.h>
#include "../ijksdl_vout.h"
#include "../ijksdl_vout_internal.h"
#include "../ffmpeg/ijksdl_vout_overlay_ffmpeg.h"

typedef struct SDL_Vout_Opaque {
    SDL_VoutDisplay_Sink sink;
} SDL_Vout_Opaque;

static SDL_VoutOverlay *linux_vout_create_overlay_l(int width, int height, Uint32 format, SDL_Vout *vout)
{
    return SDL_VoutFFmpeg_CreateOverlay(width, height, format, vout);
}

static SDL_VoutOverlay *linux_vout_create_overlay(int width, int height, Uint32 format, SDL_Vout *vout)
{
    SDL_LockMutex(vout->mutex);
    SDL_VoutOverlay *overlay = linux_vout_create_overlay_l(width, height, format, vout);
    SDL_UnlockMutex(vout->mutex);
    return overlay;
}

static void linux_vout_free_l(SDL_Vout *vout)
{
    if (!vout)
        return;

    SDL_Vout_Opaque *opaque = vout->opaque;
    if (opaque) {
        opaque->sink = 0;
    }

    SDL_Vout_FreeInternal(vout);
}

static int linux_voud_display_overlay(SDL_Vout *vout, SDL_VoutOverlay *overlay)
{
    SDL_LockMutex(vout->mutex);
    int retval = vout->opaque->sink(vout, overlay);
    SDL_UnlockMutex(vout->mutex);
    return retval;
}

static SDL_Class g_linuxwindow_class = {
    .name = "ALinuxWindow_Vout",
};

SDL_Vout *SDL_VoutLinux_Create()
{
    SDL_Vout *vout = SDL_Vout_CreateInternal(sizeof(SDL_Vout_Opaque));
    if (!vout)
        return NULL;

    SDL_Vout_Opaque *opaque = vout->opaque;
    //opaque->sink = 0;

    vout->opaque_class    = &g_linuxwindow_class;
    vout->create_overlay  = linux_vout_create_overlay;
    vout->free_l          = linux_vout_free_l;
    vout->display_overlay = linux_voud_display_overlay;

    return vout;
}

void SDL_VoutLinux_Display_Set(SDL_Vout *vout, SDL_VoutDisplay_Sink cb) {
    if (!vout)
        return;
    vout->opaque->sink = cb;
}
